package com.kenyi.co.ui.me;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.util.Util;
import com.google.gson.Gson;
import com.kenyi.co.GlideApp;
import com.kenyi.co.R;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.login.LoginPhoneActivity;
import com.kenyi.co.ui.login.RegisterActivity;
import com.kenyi.co.ui.me.bean.UserFavSettingBean;
import com.kenyi.co.ui.me.bean.UserInfoBean;
import com.kenyi.co.ui.me.ui.CollectActivity;
import com.kenyi.co.ui.me.ui.MeMainActivity;
import com.kenyi.co.ui.me.ui.MyFootActivity;
import com.kenyi.co.ui.me.ui.SettingActivity;
import com.kenyi.co.utils.CommonUtils;
import com.kenyi.co.utils.Config;
import com.kenyi.co.utils.GlideCircleBorderTransform;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * 作者：syd_123 on 2018/12/3 20:04
 * <p>
 * csdn https://blog.csdn.net/dong19900415
 */
public class MeFrament extends Fragment implements View.OnClickListener {
    private View view;
    private LinearLayout li_me_tags;
    private TextView tv_user_name, tv_me_phone, tv_me_wx;
    private TextView tv_user_fav_1, tv_user_fav_2, tv_user_fav_3;
    private ImageView iv_me_avatar, iv_me_wx_go, iv_me_phone_go;
    private Boolean is_Login = false;
    private RelativeLayout re_me_login, re_me_setting, re_me_sc, re_me_footer, re_me_phone, re_me_wx;
    private IWXAPI api;

    public MeFrament() {

    }

    public static MeFrament getInstance() {
        return new MeFrament();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.fragment_me, container, false);
        initView();

        return view;
    }

    private void initView() {
        li_me_tags = view.findViewById(R.id.li_me_tags);
        re_me_setting = view.findViewById(R.id.re_me_setting);
        re_me_footer = view.findViewById(R.id.re_me_footer);
        iv_me_wx_go = view.findViewById(R.id.iv_me_wx_go);
        iv_me_phone_go = view.findViewById(R.id.iv_me_phone_go);
        re_me_sc = view.findViewById(R.id.re_me_sc);
        re_me_login = view.findViewById(R.id.re_me_login);
        tv_user_name = view.findViewById(R.id.tv_user_name);
        iv_me_avatar = view.findViewById(R.id.iv_me_avatar);
        re_me_phone = view.findViewById(R.id.re_me_phone);
        tv_me_phone = view.findViewById(R.id.tv_me_phone);
        tv_me_wx = view.findViewById(R.id.tv_me_wx);
        re_me_wx = view.findViewById(R.id.re_me_wx);
        tv_user_fav_1 = view.findViewById(R.id.tv_user_fav_1);
        tv_user_fav_2 = view.findViewById(R.id.tv_user_fav_2);
        tv_user_fav_3 = view.findViewById(R.id.tv_user_fav_3);
        re_me_setting.setOnClickListener(this);
        re_me_sc.setOnClickListener(this);
        re_me_footer.setOnClickListener(this);
        re_me_login.setOnClickListener(this);
        re_me_phone.setOnClickListener(this);
        re_me_wx.setOnClickListener(this);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        getSmsSend();

//        String myFav = SharepUtils.getString_info(getActivity(), SharepUtils.USER_FAV_TAGS_LIST);
//        List<String>  LikeTags = SharepUtils.getShDataList(getActivity(), SharepUtils.USER_FAV_TAGS_LIST, String.class);
//
//        getLikeInfo(LikeTags);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.re_me_wx:
                if (is_Login) {

                } else {
                    api = WXAPIFactory.createWXAPI(getActivity(), Config.APP_ID_WX, true);
                    //将应用的appid注册到微信
                    api.registerApp(Config.APP_ID_WX);

                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
//                req.scope = "snsapi_login";//提示 scope参数错误，或者没有scope权限
                    req.state = "wechat_sdk_微信登录";
                    api.sendReq(req);
                }

                break;
            case R.id.re_me_phone:
                if (is_Login) {

                } else {
                    Intent melogin = new Intent(getActivity(), LoginPhoneActivity.class);
                    getActivity().startActivity(melogin);
                }

                break;
            case R.id.re_me_login:
                if (is_Login) {
                    Intent melogin = new Intent(getActivity(), MeMainActivity.class);
                    getActivity().startActivity(melogin);
                } else {
                    Intent melogin = new Intent(getActivity(), RegisterActivity.class);
                    getActivity().startActivity(melogin);
                }

                break;
            case R.id.re_me_setting:
                Intent mecontact = new Intent(getActivity(), SettingActivity.class);
                Bundle bundle = new Bundle();
                bundle.putBoolean("islogin", is_Login);
                mecontact.putExtras(bundle);
                getActivity().startActivity(mecontact);
                break;
            case R.id.re_me_sc:
                if (is_Login) {
                    Intent iv_me_sc = new Intent(getActivity(), CollectActivity.class);
                    getActivity().startActivity(iv_me_sc);
                } else {
                    Intent melogin = new Intent(getActivity(), RegisterActivity.class);
                    getActivity().startActivity(melogin);
                }

                break;
            case R.id.re_me_footer:
                if (is_Login) {
                    Intent re_me_footer = new Intent(getActivity(), MyFootActivity.class);
                    getActivity().startActivity(re_me_footer);
                } else {
                    Intent melogin = new Intent(getActivity(), RegisterActivity.class);
                    getActivity().startActivity(melogin);
                }

                break;
        }

    }

    public void getLikeInfo(List<String> myFav) {

        tv_user_fav_1.setVisibility(View.GONE);
        tv_user_fav_2.setVisibility(View.GONE);
        tv_user_fav_3.setVisibility(View.GONE);


        for (int i = 0; i < myFav.size(); i++) {
            if (i == 0) {
                tv_user_fav_1.setText(myFav.get(0));
                tv_user_fav_1.setVisibility(View.VISIBLE);
            }
            if (i == 1) {
                tv_user_fav_2.setText(myFav.get(1));
                tv_user_fav_2.setVisibility(View.VISIBLE);
            }
            if (i == 2) {
                tv_user_fav_3.setText(myFav.get(2));
                tv_user_fav_3.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 首页分类
     */
    public void getSmsSend() {

        Map<String, String> params = new HashMap<>();
        params.put("version", "2");
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", SharepUtils.getString_info(getActivity(), SharepUtils.USER_LOGIN_TOKEN));
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        String url = NetConfig.APPUSER_GETUSER;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        tv_user_name.setText("点击登录");
                        is_Login = false;
                        iv_me_avatar.setImageResource(R.drawable.iv_me_avatar);
                        re_me_wx.setVisibility(View.VISIBLE);
                        tv_me_phone.setText("去登录");
                        iv_me_phone_go.setVisibility(View.VISIBLE);
                        re_me_phone.setVisibility(View.VISIBLE);
                        tv_me_wx.setText("去登录");
                        iv_me_wx_go.setVisibility(View.VISIBLE);
                        li_me_tags.setVisibility(View.GONE);
                        SharepUtils.setString_info(getActivity(), "0", SharepUtils.USER_IS_LOGIN);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        UserInfoBean packlist = gson.fromJson(response, UserInfoBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            SharepUtils.setString_info(getActivity(), "1", SharepUtils.USER_IS_LOGIN);
                            li_me_tags.setVisibility(View.VISIBLE);
                            is_Login = true;
                            tv_user_name.setText(packlist.getDatas().getUserName());
                            if (packlist.getDatas().isBindPhone()) {
                                re_me_wx.setVisibility(View.GONE);
                                tv_me_phone.setText("已绑定");
                                iv_me_phone_go.setVisibility(View.INVISIBLE);
                            }
                            if (packlist.getDatas().isBindWeChart()) {
                                re_me_phone.setVisibility(View.GONE);
                                tv_me_wx.setText("已绑定");
                                iv_me_wx_go.setVisibility(View.INVISIBLE);
                            }
                            RequestOptions myOptions = new RequestOptions()
                                    .placeholder(R.drawable.iv_me_avatar)
                                    .optionalTransform
                                            (new GlideCircleBorderTransform(CommonUtils.dip2px(getActivity(), 0), getActivity().getResources().getColor(R.color.white)));

                            try {
                                if (Util.isOnMainThread() && getActivity() != null) {
                                    GlideApp.with(getActivity())
                                            .load(packlist.getDatas().getHeadAddress())
                                            .apply(myOptions)
                                            .into(iv_me_avatar);
                                }

                                List<String> tags = new ArrayList<String>();
                                tags = packlist.getDatas().getLikeTags();
                                if (tags!=null&&tags.size() > 0) {
                                    List<String> LikeTags = packlist.getDatas().getLikeTags();
                                    SharepUtils.setShDataList(getActivity(), SharepUtils.USER_FAV_TAGS_LIST, LikeTags);
                                    getLikeInfo(LikeTags);

                                } else {
                                    setFav();
                                }
                            } catch (Exception e) {
                            }

                        }
                    }
                });
    }

    public void setFav() {

        List<String> LikeTags = new ArrayList<String>();
        try {
            LikeTags = SharepUtils.getShDataList(getActivity(), SharepUtils.USER_FAV_TAGS_LIST, String.class);
        } catch (Exception e) {
        }
        if (LikeTags == null) {
            return;
        }
        Gson gson = new Gson();
        Map<Object, Object> map = new HashMap<>();
        map.put("userId", SharepUtils.getString_info(getActivity(), SharepUtils.USER_LOGIN_USERID));
        map.put("likeTags", LikeTags);
        String str = gson.toJson(map);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", SharepUtils.getString_info(getActivity(), SharepUtils.USER_LOGIN_TOKEN));


        String url = NetConfig.APPUSER_SETFAV;

        OkHttpUtils.postString()
                .url(url)
                .content(str)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();


                        UserFavSettingBean packlist = gson.fromJson(response, UserFavSettingBean.class);
                        int code = packlist.getCode();

                        if (code == 200) {

                            List<String> LikeTags = packlist.getDatas();
                            if (LikeTags != null && LikeTags.size() > 0) {
                                SharepUtils.setShDataList(getActivity(), SharepUtils.USER_FAV_TAGS_LIST, LikeTags);
                            }

                        }


                    }
                });
    }

}